package com.tungse.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Tungse
 * 线程是一个单独的资源类， 没有任何的附属操作
 * 1. 属性、方法
 */
public class SaleTicketDemo1 {

    public static void main(String[] args) {
        //并发  同一个资源被多个线程操作
        Ticket ticket = new Ticket();
        //lambda表达式 ()->{}
        new Thread(()->{for(int i=0; i<60; i++) {ticket.sale();}}).start();
        new Thread(()->{for(int i=0; i<60; i++) {ticket.sale();}}).start();
        new Thread(()->{for(int i=0; i<60; i++) {ticket.sale();}}).start();
    }
}

//资源类 OOP
class Ticket {
    private int ticket = 100;
    Lock lock = new ReentrantLock();
    //synchronized 本质就是排队
    public void sale() {
        lock.lock();
        try {
            if (ticket > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出第" + ticket-- + "张票" + "剩余" + ticket + "张票");
            }
        } finally {
            lock.unlock();
        }
    }
}